require 'net/http'
class Articles1Controller < ApplicationController
before_filter :authorize
  before_filter :check_editor_role, :except => [:index, :show]
  layout "newsarticles"
   uses_tiny_mce(:options => {:theme => 'advanced',
                           :browsers => %w{msie gecko},
                           :theme_advanced_toolbar_location => "top",
                           :theme_advanced_toolbar_align => "left",
                           :theme_advanced_resizing => true,
                           :theme_advanced_resize_horizontal => false,
                           :paste_auto_cleanup_on_paste => true,
                           :theme_advanced_buttons1 => %w{cut,copy,paste,pastetext,pasteword|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,media,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor},
                           :theme_advanced_buttons2 => [],
                           :theme_advanced_buttons3 => [],                         	
                           :theme_advanced_statusbar_location=>"bottom",
                           :plugins => %w{contextmenu paste preview media}},
              :content_css=> "css/content.css",
              :only => [:new, :edit, :show, :index])
  def index
    if params[:category_id]
      @articles_pages, @articles = paginate(:articles, 
        :include => :user, 
        :order => 'published_at DESC',
        :conditions => "category_id=#{params[:category_id].to_i} AND published=true")
    else
      @articles = Article.find_all_by_published(true)
      @articles_pages, @articles = paginate(:articles, 
        :include => :user,
        :order => 'published_at DESC', 
        :conditions => "published = true")        
    end
    respond_to do |wants|
      wants.html
      wants.xml  { render :xml => @articles.to_xml }
      wants.rss  { render :action => 'rss.rxml', :layout => false }
      wants.atom { render :action => 'atom.rxml', :layout => false }
    end
  end

  def show
    if is_logged_in? && @logged_in_user.has_role?('Editor')
      @article = Article.find(params[:id])
    else
      @article = Article.find_by_id_and_published(params[:id], true)
    end
    respond_to do |wants|
      wants.html
      wants.xml { render :xml => @article.to_xml }
    end
  end
  
  def new  
     curraliasn = Ualia.find_by_iscurrent(true)
    if !curraliasn.nil?
	    @article = Article.new(:user_published_by=>curraliasn.name)
	  else
	    @article = Article.new
	  end
    
        @article.body = ""
        
        @images=(params[:img].nil?)? []:params[:img].split("==");
        
                @article.imageurl = params[:cbx][0]
        
    @article.body=params[:selectiontext] unless params[:selectiontext].nil?
    
    @article.body= @article.body+"<br/>Original source "+params[:surl]
  end
  


  
  def create

		  if !(Article.find_by_title(params[:article][:title]).nil?)
		  		    flash[:notice] = "title already exists"
		  end	
    @article = Article.create(params[:article])

    
    @logged_in_user.articles << @article
    
      if (@article.title == "")||(@article.synopsis == "")
  	
  		    flash[:notice] = "title or synopsis is empty"
		  end
		  
		  if (@article.title.nil?)||(@article.synopsis.nil?)
		  	
		  		    flash[:notice] = "title or synopsis is empty"
		  end
		  
	  
    
        @test = ""

        @abc = "<br/><img src="     
    @images= params[:images]
    
  if !(@images.nil?)
      	  imgext =""
    	    	  imagefn = ""      	  
    @images.each do |image|
			   url = URI.parse(image) 	
				 Net::HTTP.start(url.host, url.port) {|http|
    	  resp = http.get(image)

    	  testfilen =""
        testfilen = image[image.rindex('/')+1,image.length-image.rindex('/')-1]
        
       if  (testfilen!="")&&(testfilen.rindex('.')!=nil)
        imgext= testfilen[testfilen.rindex('.')+1,testfilen.length-testfilen.rindex('.')-1]
       end
       
	      if ((imgext=='png')||(imgext=='jpg')||(imgext=='gif'))
	        FileUtils.mkdir_p Dir.pwd+"/public/articlesimages/"+(@article.id).to_s unless File.exists?(Dir.pwd+"/public/articlesimages/"+(@article.id).to_s)&& File.directory?(Dir.pwd+"/public/articlesimages/"+(@article.id).to_s)
	       
	       imagefn = Date.today.to_s.split('-').join('')+Time.now.to_i.to_s+"_"+rand(100).to_s+"."+imgext
	    	  File.open(Dir.pwd+"/public/articlesimages/"+(@article.id).to_s+"/"+imagefn, "wb")    	   { |file|    file.write(resp.body)   }
	    	end
   
		  }
		  image = "http://www.click2edit.com/articlesimages/"+(@article.id).to_s+"/"+imagefn
    	@imageurl = Imageurl.new
      @imageurl.article_id = @article.id
      @imageurl.simgurl = image
    	@article.imageurls<< @imageurl
    	
     image = @abc+image+">"
   	 @test = @test + image




    end    
   end
		  @imageurlobj = Imageurl.find(:first,:conditions=>["imageurls.article_id = ?",@article.id])		  
		  
		  if @imageurlobj
		   @imageurlname = @imageurlobj.simgurl
		  else
		   @imageurlname = ""
		  end

        @article.imageurl= @imageurlname
        @article.body=@test+@article.body
        @article.save
        
     params[:mymstest].each do |abcdte|
  	      @websitesinf = Websitesinf.find(abcdte)
  	      @websitesinf.articles << @article
     end

    respond_to do |wants|
      wants.html { redirect_to :controller=>'articles1',:action=>'admin' }
      wants.xml  { render :xml => @article.to_xml }
    end
  end
  
  def edit
    @article = Article.find(params[:id])
  end
  
  def update
    @article = Article.find(params[:id])
    @article.update_attributes(params[:article])
    respond_to do |wants|
      wants.html { redirect_to :controller=>'articles1',:action=>'admin' }
      wants.xml  { render :xml => @article.to_xml }
    end
  end
  
  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    respond_to do |wants|
      wants.html { redirect_to :controller=>'articles1',:action=>'admin' }
      wants.xml  { render :nothing => true }
    end
  end
  
  def admin
    @articles_pages, @articles = paginate(:articles, :order => 'published_at DESC')
  end
end
